import http.server
import socketserver
import subprocess
import re

PORT = 6001

def get_conda_version():
    """获取 Conda 版本"""
    try:
        result = subprocess.run(['conda', '--version'], capture_output=True, text=True, check=True)
        version = result.stdout.strip().split()[-1]
        return version
    except subprocess.CalledProcessError:
        return "Conda not found"

def get_conda_envs():
    """获取所有 Conda 环境名称"""
    try:
        result = subprocess.run(['conda', 'env', 'list'], capture_output=True, text=True, check=True)
        envs = result.stdout.strip().split('\n')[2:]
        envs = [line.split()[0] for line in envs if line.strip()]
        return envs
    except subprocess.CalledProcessError:
        return []

class RequestHandler(http.server.SimpleHTTPRequestHandler):
    """处理 HTTP 请求的处理程序"""
    
    def do_GET(self):
        """处理 GET 请求"""
        if self.path == '/':
            conda_version = get_conda_version()
            envs = get_conda_envs()
            
            response = f"Conda Version: {conda_version}\n"
            response += "Conda Environments:\n"
            for env in envs:
                response += f"  {env}\n"
            
            self.send_response(200)
            self.send_header("Content-type", "text/plain")
            self.end_headers()
            self.wfile.write(response.encode('utf-8'))
        else:
            super().do_GET()

def run(server_class=http.server.HTTPServer, handler_class=RequestHandler, port=PORT):
    """启动服务器"""
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print(f'Starting httpd server on port {port}...')
    httpd.serve_forever()

if __name__ == '__main__':
    run()